﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using ARS.Control.Common.EntityManage;
using ARS.Control.Custom.Entity.Fields;
using ARS.Control.Custom.Entity.Interface;

namespace ARS.Control.Custom.Entity.Model
{
    public class EntityModel
    {

        /// <summary>
        /// 编辑修改
        /// </summary>
        public const int TYPE_MODIFY = 1;
        /// <summary>
        /// 映射
        /// </summary>
        public const int TYPE_MAPPED = 2;
        /// <summary>
        /// 显示
        /// </summary>
        public const int TYPE_SHOW = 3;
        /// <summary>
        /// 搜索
        /// </summary>
        public const int TYPE_SEARCH = 4;
        /// <summary>
        /// 添加
        /// </summary>
        public const int TYPE_ADD = 5;

        public bool IsEntityUseCache { get; set; }
        /// <summary>
        /// ForeignKeyField配置
        /// </summary>
        /// <returns></returns>
        public virtual ForeignKeyConfig GetConfig_ForeignKeyConfig()
        {
            return null;
        }

        public virtual DataTable GetModelDataTable(string where, string fields = "*")
        {
            //Common.EntityManage.EntityTableInfo tableInfo = new Common.EntityManage.EntityTableInfo(this, 0);
            //Common.EntityManage.EntityToSql toSql = new Common.EntityManage.EntityToSql(this, GetEntityTableInfo());
            string sql = this.GetEntityTableInfo().EntityToSql.GetSelectSqlFields(fields, where);
            DataTable dt = ARS.DataBase.Provider.DbFactory.DbProvider.Query(sql).Tables[0];
            return dt;
        }
        public virtual int SaveToDb(bool isCheckExist = false)
        {
            return GetEntityTableInfo(TYPE_ADD).SaveAddToDb();
        }

        private List<ARS.Control.Common.EntityManage.EntityTableInfo> tableInfoList = new List<EntityTableInfo>();
        /// <summary>
        /// 实体基本信息
        /// </summary>
        public ARS.Control.Common.EntityManage.EntityTableInfo GetEntityTableInfo(int type = TYPE_MODIFY)
        {
            ARS.Control.Common.EntityManage.EntityTableInfo _EntityTableInfo = tableInfoList.SingleOrDefault(info => info.Type == type);
            if (_EntityTableInfo == null)
            {
                ;
                if (IsEntityUseCache)
                {

                    _EntityTableInfo = this.GetCacheEntityTableInfo(type);
                }
                else
                {
                    _EntityTableInfo = new ARS.Control.Common.EntityManage.EntityTableInfo(this, type);
                }
                _EntityTableInfo.Type = type;
                tableInfoList.Add(_EntityTableInfo);
            }
            return _EntityTableInfo;
        }
        private EntityTableInfo GetCacheEntityTableInfo(int type)
        {
            return new ARS.Control.Common.EntityManage.EntityTableInfo(this, type);
        }

    }
}
